#!/usr/bin/php
<?php /*
 __    __                             ____            __      
/\ \  /\ \                           /\  _`\         /\ \__   
\ `\`\\/'/  __      ___ ___      __  \ \ \L\ \    ___\ \ ,_\  
 `\ `\ /' /'__`\  /' __` __`\  /'__`\ \ \  _ <'  / __`\ \ \/  Version 4.1.2.4b
   `\ \ \/\ \L\.\_/\ \/\ \/\ \/\ \L\.\_\ \ \L\ \/\ \L\ \ \ \_ 
     \ \_\ \__/.\_\ \_\ \_\ \_\ \__/.\_\\ \____/\ \____/\ \__\
      \/_/\/__/\/_/\/_/\/_/\/_/\/__/\/_/ \/___/  \/___/  \/__/
                                                              
* major.minor.build.revision BETA

Licensed under the Creative Commons GNU General Public License 3.0 (GPL)
For licensing details, contact me or read this page:
http://creativecommons.org/licenses/GPL/2.0/
REPORT BUGS AND SUGGESTIONS TO Yamakiri
I can be contacted on the Freenode IRC network as Yamakiri.

LICENSING DETAILS:
PHP-YamaBot (IRC bot) written by Yamakiri, PseudoOne, and
segments from lizardbot by FastLizard4 (used with permission)

Copyright (C) 2008-2009 Yamakiri

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
A human-readable version of the complete license is available at
http://creativecommons.org/licenses/GPL/2.0/

*/

########################################################################
#RECOMMENDED: Check to see if the bot is being run as root##############
########################################################################
//User checking by SudoKing
$user1 = posix_getpwuid(posix_geteuid());
$pUser = $user1['name'];

switch($pUser){
	case "root":
		die("Do not run this as root!\n");
		break;
	case "toor":
		die("Do not run this as the superuser!\n");
		break;
}

$version = "4.2.0.0b";
$devMessage = "Awesome command line parameters are awesome.  Also, unless Yamakiri forgot to SVN commit a segment of code, there's now a command tracker, which keeps count of commands executed to prevent abuse!";
set_time_limit(0);
$irc_var['NULL']=NULL;

########################################################################
#NOT-RECOMMENDED: Debugging output######################################
########################################################################
error_reporting(E_PARSE | E_WARNING | E_ERROR);

#########################################################################
#REQUIRED: File Path To Configuration and functions######################
#########################################################################

$ConfigurationFile = "YamaBot.conf.php";
$CoreFunctionsFile = "core.php";
$altFunctionsFile  = "secondary.php";
$irc7datFile       = "irc7.dat.php";
if(file_exists('conf.php')){
	include_once('conf.php');
}
global $ConfigurationFile;

#########################################################################
#RECOMMENDED: Make sure the user defined a path to the configuration file
#             and the parser function, or terminate if not found.  Also,
#             terminate if terminal input is unreadable
#########################################################################

if(!$ConfigurationFile) die("Did you remember to set \$ConfigurationFile?\n");
if(!$CoreFunctionsFile) die("Did you remember to set \$CoreFunctionsFile?\n");
if(!is_readable('/dev/stdin'))	die("Input device not readable.\n");

#########################################################################
#LUXURY: Define $usage to keep track of the number of executed commands##
#########################################################################
	function usage($process){

 		global $irc_var;
 		$irc_var["usage"]++;
		$irc_var["cmd"][$irc_var["usage"]] = $process;
 		#The following limits the counter to 100 to reduce memory usage
 		if($irc_var["usage"]==100){
			$irc_var["usage"]=0;
 		}

 	}
 
 	function get_usage($params=FALSE){

 		global $irc_var;
		if($params){
 			foreach($irc_var["cmd"] as $paramTest){
 				$paramCount++;
 				if($paramTest == $params){
 					$cmd_impld = "#" . $paramCount . ": " . $irc_var["cmd"][$paramCount];
 				}
 			}
 		} else {
 			$cmd_impld = implode(" ",$irc_var['cmd']);
 		}
 		return $cmd_impld;
 	}

#########################################################################
#RECOMMENDED: Let users add startup paramaters###########################
#########################################################################

#NOTE: I have set this up so that $args=$argv because of the array like
#      nature of $argv.  I had intended to set it equal to a single part
#      of the array, from where we take arguements

if($argc==2){
	$args = $argv[1];
}

switch($args){

	case "-h":
	case "-help":
	case "--help":
	case "--h":
		echo "\r\n";
		echo "Currently supported command line options are:\r\n";
		echo "\t* help   - outputs this help text\r\n";
		echo "\t* hash   - outputs a sha512 hash, helpful in the configuration file\r\n";
		echo "\t* updates- checks to see if your bot is in need of updates\r\n";
		echo "\t* new    - what's new this release\r\n";
		echo "\t* param  - startup paramaters to use instead of setup if you use screen\r\n";
		echo "\t* cron   - Puts the bot in your crontab file\r\n";
		echo "\r\n";
		echo "It is highly recommended that you take a look at -param and the README file\r\n";
		echo "\r\n";
		
		die();
		break;

	case "-hash":

		//This snippet was written by SudoKing. Thanks ;)
		echo "\r\nPlease enter password to create hash for use in the config file: ";
		while(!$pass){
		        $h = fopen('/dev/stdin','r');
        		$i = trim(fgets($h,64));
        		$hash = hash('sha512',$i);
        		echo "Hash is: $hash\r\n\r\n";
        		fclose($h);
        		exit();
        	}
		die();
		break;
	case "-egg":
	case "-eggs":
	case "-easterEgg":
		echo "\r\n";
		echo <<<EGG
[20:21:47] <@Yamakiri> [20:18:33] <+Yamakiri> Emachman: omg we forgot 
	to code bot birth control pills!

[20:21:47] <@Yamakiri> [20:18:38] <+Pianista|ce> Until_It_Sleeps: Ple
	nty of bots go to the loo.

[20:21:47] <@Yamakiri> [20:18:42] <+Pianista|ce> In the UK, that is.
[20:21:47] <@Yamakiri> [20:18:48] <+Emachman> :O
[20:21:47] <@Yamakiri> [20:18:56] <+NocturneNoir> grah
[20:21:47] <@Yamakiri> [20:19:05] <+Yamakiri> YamaBot: quit talking 
	to that boy, you know he's trouble

[20:21:47] <@Yamakiri> [20:19:05] -!- YamaBot [n=YamaBot@unaffiliated
	/yamakiri/bot/yamabot] has quit ["talking to that boy, you kn
	ow he's
	trouble"]

[20:21:59] <+Suiseiseki[prpl]> Good thing I kept sometings to myself
[20:22:01] -!- YamaBot [n=YamaBot@unaffiliated/yamakiri/bot/yamabot] 
	has quit [Client Quit]

[20:22:05] <+Eulalia> rotfl
[20:22:06] <@Yamakiri> ofu**
[20:22:09] <+Suiseiseki[prpl]> dang I will be introuble
[20:22:16] <+Eulalia> he killed Yamabot XDXDXD
EGG;
		die("\r\n\r\n");
		break;
	case "-update":
	case "-updates":
		//Attributed to FastLizard4
		echo chr(27) . "[01;93mChecking for updates...\r\n";
		$upfp = fopen('http://yamabot.googlecode.com/svn/trunk/YamaBot/latest.dat', 'r');
		$data = str_replace(array("\r","\n"),'',fgets($upfp));
		fclose($upfp);
		
		if(!$data) {
			echo chr(27) . "[1mCheck for updates failed!" . chr(27) . "[0m\r\n";
		}
		if($data==$version){
			echo chr(27) . "[01;92mYou have the latest version, {$version}" . chr(27) . "[0m\r\n";
		} else {
 			echo chr(27) . "[01;91mYou do not have the latest version, {$data}" . chr(27) . "[0m\r\n";
		}
		die();
		break;
	case "-param":
	case "-params":
		echo "\r\n";
		echo "The YamaBot development crew worked hard so that there are a multitude of ways to pass paramaters to the bot.\r\n";
		echo "The key reason for this was the ability to screen the application without a long, unscreanable input process\r\n";
		echo "\r\n";
                echo "The parameters are as follows (Please note that there are lots of aliases built in):\r\n";
                echo "\t -a - The administrative password (Defaults to \"foobar\" without quotes) [REQUIRED]\r\n";
                echo "\t -n - The network to connect to (ex. irc.tyronet.org) Defaults to irc.freenode.net [REQUIRED]\r\n";
                echo "\t -w - The NickServ authentication password [NOT required]\r\n";
                echo "\t -b - The bot's IRC nick (Defaults to YamaBot-{random number}) [RECOMMENDED]\r\n";
                echo "\t -g - The bot's \"GECOS\" or \"Realname\" (Defaults to the SVN URL) [RECOMMENDED]\r\n";
                echo "\t -i - The bot's ident (Defaults to \"YamaBot\") [RECOMMENDED]\r\n";
                echo "\t -c - The list of channels for the bot to join (Defaults to \"#YamaBot\" [RECOMMENDED]\r\n";
		echo "\t -d - The bot's debugging channel (Default is in the terminal) [for advanced users]\r\n";
		echo "\t -r - Turn on autorejoin (Defaults to \"no\"; Values are \"yes\" and \"no\" [RECOMMENDED\r\n";
		echo "\t -p - The port the bot should connect on [RECOMMENDED]";
		echo "\r\n";
#               echo "For a full list of aliases, type: ./yamabot -aliases\r\n";
		echo "Remember to prefix each with a dash.\r\n";
		echo "EXAMPLE: php YamaBot.php -admin foobar -network irc.freenode.net -nick YamaBot -chans ##boters -auto yes\r\n";
		echo "\r\n";
		die();
		break;
	case "-cron":
	case "-crontab":
	case "-cronAdd":
		$dirname = dirname(__FILE__);
		$dirnameArr = explode("/",$dirname);
		$j = 0;
		for($i=0;$i<2;$i++){
			if($dirnameArr[$i] == 'home'){
				$homeDir = $dirnameArr[$i];
			} else {
				echo "Couldn't find your home directory.\r\n";
				echo "Please input: \r\n";
				while(!$data){
					$handle = fopen('/dev/stdin','r');
					$data   = trim(fgets($handle,75));
					$homeDir= $data;
					fclose($handle);
				}
			}
		}
		$_file = __FILE__;
		if(file_exists($homeDir.'/phoenix')){
			file_put_contents($homeDir."/crontab","* * * * * ".$homeDir."/phoenix /tmp/".$pUser."-phoenix /usr/bin/php ".$_file.">/dev/null 2>&1");
		} elseif(file_exists('/usr/local/bin/phoenix')) {
			file_put_contents($honeDir."/crontab","* * * * * ".$homeDir."/phoenix /tmp/".$pUser."-phoenix /usr/bin/php ".$_file.">/dev/null 2>&1");
		} else {
			echo "Could not find phoenix.  Please read the phoenix file or the README file\r\n";
		}
		shell_exec("crontab ".$dirname."/crontab");
		die("\r\nOperation Successful!\r\n");
		break;
}

#########################################################################
#REQUIRED: Upload the configuration file specified above#################
#########################################################################

echo "Loading Configuration and Class files...\n";

require_once($ConfigurationFile );
require_once($CoreFunctionsFile );
include_once($altFunctionsFile  );
include_once($irc7datFile       );

#########################################################################
#HIGHLY-REOMMENDED: Command Line Startup Parameters, which took forever
#                   to code, just for you
#########################################################################
// Painstaking credit goes to Yamakiri

if($argc>2){

$getopt = "a:b:c:d:g:i:n:p:r:w:";
$opts   = getopt( $getopt );
foreach( $opts as $x => $y ) {
	while($k = array_search( "-" . $x, $argv)){
		if($k){ 
			unset($argv[$k]); 
		}
		if(preg_match("/^.*".$x.":.*$/i", $getopt)){
			unset($argv[$k+1]);
		}
	}
}
$argv = array_merge( $argv );

foreach( $opts as $case => $param ) {

	switch ($case) {

		case 'a':
			$values['a'] = $param;
			$adminPass = $param;
			if(hash('sha512',$adminPass)!=$realpass){
				die("[403] Permission Denied. Invalid password.\n"); 
			}
			$input['adminPass'] = TRUE;
			break;
		
		case 'b':
			$values['b'] = $param;
			$irc_var['botnick'] = $param;
			$botnick = $irc_var['botnick'];
			$input['botnick'] = TRUE;
			break;

		case 'c':
			$values['c'] = $param;
			$irc_var['chans'] = $param;
			$input['chans'] = TRUE;
			break;

		case 'd':
			$values['d'] = $param;
			$irc_var['debugChan'] = $param;
			$input['debugChan'] = TRUE;
			break;

		case 'g':
			$values['g'] = $param;
			$irc_var['GECOS'] = $param;
			$input['GECOS'] = TRUE;
			break;

		case 'i':
			$values['i'] = $param;
			$irc_var['ident'] = $param;
			$input['ident'] = TRUE;
			break;

		case 'n':
			$values['n'] = $param;
			$irc_var['network'] = $param;
			$input['network'] = TRUE;
			break;

		case 'p':
			$values['p'] = $param;
			$irc_var['port'] = $param;
			$input['port'] = TRUE;
			break;
		
		case 'r':
			$values['r'] = $param;
			$irc_var['autoRejoin'] = $param;
			$input['autoRejoin'] = TRUE;
			break;

		case 'w':
			$values['w'] = $param;
			$irc_var['NickServPass'] = $param;
			$input['NickServPass'] = TRUE;
			break;	
	}
}

	if(!$input['adminPass'] && php_sapi_name() != 'cli'){
		die("[403] Permission Denied.  You likely forgot to input the administrative password.  Please run ./YamaBot.php -param\r\n");
	}
        if($irc_var['network'] == "" || !$input['network']){
               $irc_var["network"] = "irc.freenode.net";
       }
        if($irc_var['port'] == "" || !$input['port']){
                $irc_var["port"] = 6667;
        }
	if($irc_var['botnick'] == "" || !$irc_var['botnick'] || !$input['botnick']){
		$randAppend = rand(0,9999);
		$botnick = "YamaBot" . $randAppend;
	}
	if($irc_var['NickServPass'] == "" || !$input["NickServPass"]){
		$irc_var["NickServPass"] = FALSE;
	}
	if($irc_var['GECOS'] == "" || !$input["GECOS"]){
		$irc_var["GECOS"] = "http://code.google.com/p/yamabot";
	}
	if($irc_var['ident'] == "" || !$input["ident"]){
		$irc_var["ident"] = "YamaBot";
	}
	if($irc_var['chans'] == "" || !$input["chans"]){
		$irc_var["chans"] = "#YamaBot";
	}
	$input["PRE"] = TRUE;
}

#$irc_var = array_merge( $irc_var, $config );
########################################################################
#NOTE: This notifies the user that the prompt will begin ###############
########################################################################
if(!$input["PRE"]){

echo "\nWelcome to the YamaBot connection interface.  You will be asked a few questions to run the bot.  Hit return to 
accept the defaults (except for password).\n\n";

#########################################################################
#SECURITY: This is a critical piece of the bot which prevents unauthorized
#          running of the bot.  The $adminPass is defined in your config
#          file with sha512 encryption. This segment will prompt the
#          code's activating user to input your password if the user is
#          accessing this from the web.
#########################################################################
if(php_sapi_name() != 'cli'){
	echo "Access attempt by non-cli user detected!\r\nPlease enter your pass to continue starting the bot: "; 

	while(!$adminPass){
		$handle = fopen('/dev/stdin','r');
		$adminPass = trim(fgets($handle,32));
		if(hash('sha512',$adminPass)!=$realpass){
			die($color['red'] . "[403]" . $color['none'] . " Permission Denied. Invalid password.\n");
		}
		fclose($handle);
	}
}
#########################################################################
#RECOMMENDED: Request input of password, network, and port then, clear the
#             screen
#########################################################################

include("YamaBot.bak.php"); #Reboot from this file if there is a SIGINT (Control C/^C at terminal)
if($sigint){ usleep(500); file_put_contents("YamaBot.bak.php","<?php \$sigint = false; ?>"); }

if(!$irc_var["network"]) echo "Please input network address to connect: ";
while(!$irc_var["network"]){
	$handle = fopen('/dev/stdin','r');
	$irc_var["network"] = trim(fgets($handle,32));
	if($irc_var["network"] == ""){
		$irc_var["network"] = "irc.freenode.net";
	}
	fclose($handle);
}

if(!$irc_var["port"]) echo "Please input port to connect on: ";
while(!$irc_var["port"]){
	$handle = fopen('/dev/stdin','r');
	$irc_var["port"] = trim(fgets($handle,32));
	if(strlen($irc_var["port"])>5){
		die("Invalid port specified. (Greater than 5 characters)\n");
	}
	if($irc_var["port"] == ""){
		$irc_var["port"] = 6667;
	}
	fclose($handle);
}

$botnick = $irc_var['botnick'];
if(!$botnick) echo "Please enter nickname for bot to use: ";
while(!$botnick){
	$handle = fopen('/dev/stdin','r');
	$botnick = trim(fgets($handle,32));
	if($botnick == ""){
		$randAppend = rand(0,9999);
		$botnick = "YamaBot".$randAppend;
	}
	fclose($handle);
	$irc_var["botnick"] = $botnick;
}

if(!$irc_var["NickServPass"]) echo "Please input NickServ Password: ";
while(!$irc_var["NickServPass"]){
        $handle = fopen('/dev/stdin','r');
        $irc_var["NickServPass"] = trim(fgets($handle,50));
	if($irc_var["NickServPass"] == ""){
		$irc_var["NickServPass"] = FALSE;
		fclose($handle);
		break;
	}
        fclose($handle);
}

if(!$irc_var["GECOS"]) echo "Please enter GECOS: ";
while(!$irc_var["GECOS"]){
	$handle = fopen('/dev/stdin','r');
	$irc_var["GECOS"] = trim(fgets($handle,50));
	if($irc_var["GECOS"] == ""){
		$irc_var["GECOS"] = "http://code.google.com/p/yamabot";
	}
	fclose($handle);
}

if(!$irc_var["ident"]) echo "Please enter IDENT: ";
while(!$irc_var["ident"]){
        $handle = fopen('/dev/stdin','r');
        $irc_var["ident"] = trim(fgets($handle,32));
	if($irc_var["ident"] == ""){
		$irc_var["ident"] = "YamaBot";
	}
        fclose($handle);
}

if(!$irc_var["chans"]) echo "Please enter channels to join (Separate by \",\") (e.g #foo,#bar): ";
while(!$irc_var["chans"]){
	usleep(500);
	$handle = fopen('/dev/stdin','r');
	$irc_var["chans"] = trim(fgets($handle,250));
	if($irc_var["chans"] == ""){
		$irc_var["chans"] = "#YamaBot";
	}
	fclose($handle);
}
/*
if(!$irc_var["debugChan"]) echo "Please the Debugging channel (leave blank for none): ";
while(!$irc_var["debugChan"]){
	$handle = fopen('/dev/stdin','r');
	$irc_var["debugChan"] = trim(fgets($handle,50));
	if($irc_var["debugChan"] == ""){
		$irc_var["debugChan"] = FALSE;
		fclose($handle);
	}
	fclose($handle);
	$debugChan = $irc_var["debugChan"];
}

global $debugChan;
*/
if(!$irc_var["autoRejoin"]) echo "Turn AutoRejoin On? (\"yes\" or \"no\"): ";
while(!$irc_var["autoRejoin"]){
        $handle = fopen('/dev/stdin','r');
        $irc_var["autoRejoin"] = trim(fgets($handle,4));
	if($irc_var["autoRejoin"] == ""){
		$irc_var["autoRejoin"] = "off";
	}
        fclose($handle);
}
#$irc_var = array_merge( $irc_var, $config );
} #close if(!$input["PRE"]

global $irc_var; #make the critical $irc_var[] array global

#########################################################################
#HIGHLY-RECOMMENDED: Functions, which cannot be defined inside the 
#                    while loop. Appoligies for the awkward placement
#########################################################################

function debug_out(&$debug,$output,&$channel){

	global $nick,$irc,$debugChan,$irc_var;

	if($debugChan){

	switch($debug){
		case "wikilink":
			fwrite($irc,"PRIVMSG $debugChan :Link- ".substr(join(" , ",$output),3)." for $nick\r\n");
			break;
		case "echo":
			fwrite($irc,"PRIVMSG $debugChan :ECHO: $output -TO- $channel -BY- $nick\r\n");
			break;
		case "do":
			fwrite($irc,"PRIVMSG $debugChan :DO: $output -TO- $channel -BY- $nick\r\n");
			break;
		case "notice":
			fwrite($irc,"PRIVMSG $debugChan :NOTICE: $output -TO- $channel -BY- $nick\r\n");
			break;
		case "join":
			fwrite($irc,"PRIVMSG $debugChan :JOIN: $output -BY- $nick\r\n");
			break;
		case "part":
			fwrite($irc,"PRIVMSG $debugChan :PART: $output -BY- $nick\r\n");
			break;
		case "rejoin":
			fwrite($irc,"PRIVMSG $debugChan :REJOIN: $output -BY- $nick\r\n");
			break;
		case "off":
			fwrite($irc,"PRIVMSG $debugChan :BOT MUTE ORDERED -BY- $nick\r\n");
			break;
		case "on":
			fwrite($irc,"PRIVMSG $debugChan :BOT ON ORDERED -BY- $nick\r\n");
			break;
		case "eval":
			fwrite($irc,"PRIVMSG $debugChan :EVAL (\$eval contents: $output" . ") ISSUED -BY- $nick\r\n");
			break;
		case "quit":
			fwrite($irc,"PRIVMSG $debugChan :QUIT -MESSAGE- $output -- ISSUED -BY- $nick\r\n");
			break;
		case "amsg":
			fwrite($irc,"PRIVMSG $debugChan :AMSG: $output -BY- $nick\r\n");
			break;
		case "notify_kick":
			fwrite($irc,"PRIVMSG $debugChan :KICK: $output\r\n");
			break;
		case "restart":
			fwrite($irc,"PRIVMSG $debugChan :Restarting - $output\r\n");
			break;
		case "remove":
			fwrite($irc,"PRIVMSG $debugChan :\0034 $output\r\n");
			break;
		case "history":
			fwrite($irc,"PRIVMSG $debugChan :HISTORY: $output -TO- $channel -BY- $nick\r\n");
			break;
		case "mystats":
			fwrite($irc,"PRIVMSG $debugChan :MYSTATS: $output -TO- $channel -BY- $nick\r\n");
			break;

	} #switch
	} elseif(!$debugChan) {

	switch($debug){
		case "wikilink":
			echo "Link- ".substr(join(" , ",$output),3)."for $color1\r\n";
			break;
		case "echo":
			echo "ECHO: $output -TO- $channel -BY- $nick\r\n";
			break;
		case "do":
			echo "DO: $output -TO- $channel -BY- $nick";
			break;
		case "notice":
			echo $color['yellow'] . "NOTICE:" . $color['none'] . " $output -TO- $channel -BY- $nick\r\n";
			break;
		case "join":
			echo "JOIN: $output -BY- $nick\r\m";
			break;
		case "part":
			echo "PART: $output -BY- $nick\r\n";
			break;
		case "rejoin":
			echo "REJOIN: $output -BY- $nick\r\n";
			break;
		case "off":
			echo $color['red'] . "BOT MUTE ORDERED -BY- $nick" . $color['none'] . "\r\n";
			break;
		case "on":
			echo $color['blue'] . "BOT ON ORDERED -BY- $nick" . $color['none'] . "\r\n";
			break;
		case "eval":
			echo "EVAL (\$eval contents: $output" . ") ISSUED -BY- $nick\r\n";
			break;
		case "quit":
			echo "QUIT -MESSAGE- $output -- ISSUED -BY- $nick\r\n";
			break;
		case "amsg":
			echo "AMSG: $output -BY- $nick\r\n";
			break;
		case "notify_kick":
			echo "KICK: $output\r\n";
			break;
		case "restart":
			echo "RESTART: $output\r\n";
			break;
		case "remove":
			echo "REMOVE: $output\r\n";
			break;
		case "history":
			echo "HISTORY: $output -TO- $channel -BY- $nick\r\n";
			break;
		case "mystats":
			echo "MYSTATS: $output -TO- $channel -BY- $nick\r\n";
			break;
	} #switch
	} #else 
} #end function

$rehash = FALSE;

echo "Preparing signal handlers...\r\n";

declare(ticks = 1);

function SIGTERM(){
	global $irc;
	fwrite($irc, "QUIT :Caught SIGTERM (Termination Request)\r\n");
	sleep(3);
	fclose($irc);
	die("Caught SIGTERM\r\n");
}
function SIGHUP(){
	global $ConfigurationFile;
	echo "-!- Caught SIGHUP, rehashing now\r\n";
	$rehash = TRUE;
	include($ConfigurationFile);
	$rehash = FALSE;
	echo "-!- Rehash complete.\r\n";
}
function SIGINT(){
	global $irc,$irc_var;
	echo "Writing to backup...\r\n";
	$sigintOut = "<?php
	\$irc_var[\"botnick\"]   = \"" . $irc_var["botnick"]   . "\";
	\$irc_var[\"network\"]   = \"" . $irc_var["network"]   . "\";
	\$irc_var[\"port\"]      = "   . $irc_var["port"]      .   ";
	\$irc_var[\"GECOS\"]     = \"" . $irc_var["GECOS"]     . "\";
	\$irc_var[\"ident\"]     = \"" . $irc_var["ident"]     . "\";
	\$irc_var[\"chans\"]     = \"" . $irc_var["chans"]     . "\";
	\$irc_var[\"debugChan\"] = \"" . $irc_var["debugChan"] . "\";
	\$irc_var[\"autoRejoin\"]= \"" . $irc_var["autoRejoin"]. "\";
	\$sigint               = true;
?>";							   
	file_put_contents("YamaBot.bak.php",$sigintOut);
	fwrite($irc, "QUIT :Caught SIGINT (^C) at terminal (this is a forceful exit)\r\n");
	echo "CAUGHT SIGINIT (^C / Control C) AT TERMINAL\r\n";
	echo "*** DISCONNECTING ".$irc_var["network"].":".$irc_var["port"]."\r\n";
	fclose($irc);
	die("Caught SIGINT\r\n");
}
function SIGUSR1(){
	flush();
}

echo "\nInitializing Signal Handlers...\n";

pcntl_signal(SIGTERM, "SIGTERM");
pcntl_signal(SIGHUP,  "SIGHUP" );
pcntl_signal(SIGINT,  "SIGINT" );
pcntl_signal(SIGUSR1, "SIGUSR1");
#########################################################################
#REQUIRED: Define $irc, the network and port are previously defined######
#########################################################################

$irc = fsockopen($irc_var["network"], $irc_var["port"], $irc_var["ircerrno"], $irc_var["ircerrstr"], 15);

if(!is_resource($irc)){
	die("-!- Could not connect to IRC (Error $ircerrno) { $ircerrstr }\n");
}

global $irc;

#########################################################################
#REQUIRED: Write our username and user information to the IRC network####
#########################################################################

fwrite($irc,"NICK $botnick\r\n");
	echo ">> NICK $botnick\n";

fwrite($irc,"USER " . $irc_var["ident"] . " * 8 :" . $irc_var["GECOS"] . "\r\n");
	echo "USER " . $irc_var["ident"] . " * 8 :" . $irc_var["GECOS"] . "\r\n";

#########################################################################
#REQUIRED: Start the while loop which lets us connect to the IRC network#
#########################################################################

while(!feof($irc)){

#########################################################################
#REQUIRED: Define $data, what we get from the network, and remove newlines
#########################################################################

	$data = str_replace(array("\n","\r"),'',fgets($irc,1024));

	global $data;

#########################################################################
#HIGHLY-RECOMMENDED: Define critical variables for the bot, some functions
#                    may break without them
#########################################################################

	if($data != ""){

		   $arr    = explode("!",$data);
		$thesender = $arr[0];
		  $chana1  = explode("PRIVMSG ",$data);
		  $chana   = $chana1[1];
		  $chanb   = explode(" :",$data);
		   $msg    = $chanb[1];
		  $idata   = "<$thesender>$msg";
		  $chana   = explode("PRIVMSG ",$data);
		  $chana1  = $chana[1];
		  $chanb   = explode(" :",$chana1);
		  $chanc   = $chanb[0];
		 $channel  = $chanc;
		  $target  = explode("!",$d[0]);
		   $target = trim($target[0],":");
		  $nicka   = $n[0];
		 $realnick = explode("!",$nicka);
		 $hostmask = $realnick[1];
		  $nick1   = $realnick[0];
		   $nick   = trim($nick1,':');
		   $full   = $hostmask;
		  $ident1  = explode("@",$full);
		   $host   = $ident1[1];
		  $ident   = $ident1[0];
		  $buffer  = $data;

		global $hostmask,$channel,$target,$host,$nick,$ident;

		echo "\r\n[".date("h:i:s")."]".$data."\r\n";
	}

	$d = explode(' ',$data);
	$n = explode(" ",$data);
		$p = str_replace(":","",$data);
		$p = str_replace("$$","",$p);
		$p = explode(' ',$p);
		$nicka = $n[0];
		$realnick = explode("!",$nicka);
		$nick1 = $realnick[0];
		$nick = trim($nick1,':');
		$color = "\002\0034[\003\002 $nick \0034\002]\003\002";

	global $d,$n;

#########################################################################
#REQUIRED: respond to PINGs from the server with PONG ###################
#########################################################################

	if(strtolower($d[0]) == 'ping'){
		fwrite($irc,"PONG ".$d[1]."\r\n");
		echo ">>> PONG!\n";
	}

#########################################################################
#RECOMMENDED: join channels on connect ##################################
#########################################################################

	if(($d[1] == '376') || ($d[1] == '422') && $irc_var["NickServPass"]){
		fwrite($irc,"PRIVMSG NickServ :IDENTIFY " . $irc_var["NickServPass"] . "\r\n"); 
		fwrite($irc,"MODE $botnick +I\r\n");
		$connected=1;
	}

	if(!$irc_var["NickServPass"] && !$isIdentified && !$connected){
		//This bit is a workaround for users who don't ID with NickServ
		$joinUncloaked = TRUE;
	}

	if(($d[1] == "901" || ($joinUncloaked && !$connected && !$isIdentified)) && !$joinedChans){
		fwrite($irc,"JOIN ".$irc_var["chans"]."\r\n");
		fwrite($irc,"JOIN ".$irc_var["debugChan"]."\r\n");

		$joinUncloaked = FALSE;
		$joinedChans   = TRUE;
	}


#########################################################################
#RECOMMENDED: Identify with the nickserv password, then unset and destroy
#             the variable for protection purposes
#########################################################################


	if($connected){ 
		unset($irc_var["NickServPass"]);
		$connected=0;
		$isIdentified=TRUE;
	}

#########################################################################
#RECOMMENDED: The following will cause the bot to append an underscore to
#             its nick if the username is in use, and then attempt to ghost
#             the offending bot/connection/user (by SudoKing)
#########################################################################

	if($d[1] == "433"){
		$originalNick = $botnick;
		$nickname = $botnick;
		fputs($irc,"NICK $nickname"."_\r\n");
		$doGhost = true;
	}

	if($doGhost && $isIdentified){
		fputs($irc,"NickServ GHOST $originalNick $NickServPass\r\n");
		sleep(1);
		fputs($irc,"NICK $originalNick\r\n");
		$doGhost = false;
	}

#########################################################################
#NOTE: Here lies the main body of YamaBot.  YamaBot has its code organized
#      based on the canUse array configuration file order, ex. link, do,
#      echo, etc.  The devs recommend you keep it that way.
#########################################################################

	####################################
	#        Wiki Link Function
	####################################

        $messageA = explode("PRIVMSG $channel :",$data);
        $message  = $messageA[1];
	(array)$wikiLinkArr = array("");
	$noLink = "/(\{\{so(.*)fix(.*)it\}\}|\{\{done(.*)\}\}|\{\{fact\}\})/i";
	if(preg_match_all('/\[\[(.*?)\]\]/', $message, $matches) && !preg_match($noLink,$data) && hasPriv('link')){
                $nicka    = $n[0];
                $realnick = explode("!",$nicka);
                $nick1    = $realnick[0];
                $nick     = trim($nick1,':');
                $color1   = "\002\0034[\003\002 $nick \0034\002]\003\002";
		foreach($matches[1] as $wikiLink){
			if(stristr($wikiLink,"|")){ 
				$wikiLink = explode("|",$wikiLink);
				$wikiLink = $wikiLink[0];
			}
			$wikiLink = str_replace(" ","_",$wikiLink);
			$wikiLink = str_replace("[","",$wikiLink);
			$wikiLink = str_replace("]","",$wikiLink);
			$wikiLink = str_replace("?","",$wikiLink);
			$wikiLink = str_replace(array("[","]","?","{","}"),"",$wikiLink);
			$wikiLink = trim($wikiLink,"-");
			$wikiLink = urlencode($wikiLink);
			$wikiLink = str_replace("%2F","/",$wikiLink);
			$wikiLink = str_replace("%3A",":",$wikiLink);
			if(!in_array($wikiURL.$wikiLink,$wikiLinkArr)){
				$wikiLinkArr[] = $wikiURL.$wikiLink;
			}
		}
		$sizeOfWikiLinkArr = count($wikiLinkArr);
		$sizeOfWikiLinkArr = $sizeOfWikiLinkArr - 1;
		if($sizeOfWikiLinkArr==1){
			fwrite($irc,"PRIVMSG $channel :\00314[[\003\0037{$matches[1][0]}\003\00314]]\003 \0034Link\003 \0035*\003 \0039$nick\003 \0035*\003 \0032".$wikiURL.$wikiLink."\003\r\n");
		} elseif(count($wikiLinkArr>1)) {
			fwrite($irc,"PRIVMSG $channel :$color1: ".substr(join(" , ",$wikiLinkArr),3)."\r\n");
		} else {
			fwrite($irc,"PRIVMSG $channel :$color1: ".substr(join(" , ",$wikiLinkArr),3)."\r\n");
		}
		$debug = "wikilink";
		debug_out($debug,$wikiLinkArr,$channel);
		unset($wikiLinkArr);
		usage($debug);
	}

	####################################
	#        Template Link Function
	####################################

        $messageA = explode("PRIVMSG $channel :",$data);
        $message  = $messageA[1];
        $wikiLinkArr = Array("");
        if(preg_match_all('/\{\{(.*?)\}\}/', $message, $matches) && !preg_match($noLink,$data) && hasPriv('link')){
                $nicka    = $n[0];
                $realnick = explode("!",$nicka);
                $nick1    = $realnick[0];
                $nick     = trim($nick1,':');
                $color1   = "\002\0034[\003\002 $nick \0034\002]\003\002";
		foreach($matches[1] as $wikiLink){
			if(stristr($wikiLink,"|")){ 
				$wikiLink = explode("|",$wikiLink);
				$wikiLink = $wikiLink[0];
			}
			$wikiLink = str_replace(" ","_",$wikiLink);
			$wikiLink = str_replace("[","",$wikiLink);
			$wikiLink = str_replace("]","",$wikiLink);
			$wikiLink = str_replace("?","",$wikiLink);
			$wikiLink = str_replace(array("[","]","?","{","}"),"",$wikiLink);
			$wikiLink = trim($wikiLink,"-");
			$wikiLink = urlencode($wikiLink);
			$wikiLink = str_replace("%2F","/",$wikiLink);
			$wikiLink = str_replace("%3A",":",$wikiLink);
			if(!in_array($wikiURL."Template:".$wikiLink,$wikiLinkArr)){
				$wikiLinkArr[] = $wikiURL."Template:".$wikiLink;
			}
		}
		fwrite($irc,"PRIVMSG $channel :$color1: ".substr(join(" , ",$wikiLinkArr),3)."\r\n");
#		fwrite($irc,"PRIVMSG $channel :$color1: ".join(" , ",$wikiLinkArr)."\r\n");
		unset($wikiLinkArr);
		$debug = "wikilink";
		debug_out($debug,$wikiLinkArr,$channel);
		usage($debug);
	}

	####################################
	#           Echo Function
	####################################

        if(stripos($data,"$botnick: echo") && hasPriv('echo')){
                $echoArr = explode("$botnick: echo ",$data);
                $echo    = $echoArr[1];
                fwrite($irc,"PRIVMSG $channel :$echo\r\n");
		$debug = "echo";
		debug_out($debug,$echo,$channel);
		usage($debug);
        }

        ####################################
        #            Do Function
        ####################################

	if(stripos($data,"$botnick: do") && hasPriv('do')){
		$doArr = explode("$botnick: do ",$data);
		$do    = $doArr[1];
		fwrite($irc,"PRIVMSG $channel :" . chr(001) . "ACTION $do" . chr(001) . "\r\n");
		$debug = "do";
		debug_out($debug,$do,$channel);
		usage($debug);
	}

        ####################################
        #          Notice Function
        ####################################

	if(stripos($data,"$botnick: notice") && hasPriv('notice')){
		$noticeArr = explode("$botnick: notice ",$data);
		$notice    = $noticeArr[1];
		fwrite($irc,"NOTICE $channel :$notice\r\n");
		debug_out($debug,$notice,$channel);
		usage($debug);
	}

	####################################
	#            Join Function
	####################################
	
	if(stripos($data,"$botnick: join") && hasPriv('join')){
		$joinArr = explode("$botnick: join ",$data);
		$join    = $joinArr[1];
		fwrite($irc,"JOIN $join\r\n");
		$irc_var["chans"] .= "," . $join;

		$debug = "join";
		debug_out($debug,$join,$channel);
		usage($debug);
	}

        ####################################
        #           Part Function
        ####################################

	if(stripos($data,"$botnick: part") && hasPriv('part')){
		$partArr = explode("$botnick: part ",$data);
		$i = 0;
		if(stripos($data,"#")){
			if(stristr($partArr[0],"#")){
				$partChan = $partArr2[0];
			} elseif(stristr($partArr[0])) {
				$partChan = $partArr[1];
				$part1 = TRUE;
			}
		} else { $partChan = $channel; }
		if($part1){
			 $partMsg = $partArr[2];
		} else { $partMsg = $partArr[1]; }
		$part    = $partChan;
		fwrite($irc,"PART $partChan :$partMsg\r\n");
		$chansArr = explode(",",$irc_var["chans"]);
		foreach($chansArr as $key){
			if(stripos($channel,$chansArray)){
				unset($chansArray[$i]);
				$irc_var["chans"] = join(",",$chansArr);
			}
			$i++;
		}
		$debug = "part";
		debug_out($debug,$part,$channel);
		usage($debug);
	}

        ####################################
        #          Rejoin Function
        ####################################

	if(stripos($data,"$botnick: rejoin") && hasPriv('rejoin')){
		$rejoinArr  = explode("$botnick: rejoin ",$data);
		$rejoin     = $rejoinArr[1];

                $thisChanA  = explode("PRIVMSG ",$data);
                $thisChanA1 = $chana[1];
                $thisChanB  = explode(" :",$chana1);
                $thisChanC  = $chanb[0];
                $thisChan   = $chanc;


		if(($rejoin==" " || $rejoin=="") && strlen($rejoin)<2){
			fwrite($irc,"PART $thisChan\r\n");
			sleep(1);
			fwrite($irc,"JOIN $thisChan\r\n");
		} else { 
			fwrite($irc,"PART $rejoin\r\n");
			sleep(1);
			fwrite($irc,"JOIN $rejoin\r\n");
		}
		$debug = "rejoin";
		debug_out($debug,$rejoin,$channel);
		usage($debug);
	}

	####################################
	#        IRC7 help functions
	####################################

	if(stripos($data,"$botnick: help") && hasPriv('help')){
		$myTopic=explode("$botnick: help ",$data);
		$myTopic=$myTopic[1];

		switch($myTopic){
			case "index":
			case "all":
				fwrite($irc,"PRIVMSG ".(($channel==$botnick)?"$nick ":"$channel "). ":$nick, ".help("index")."\r\n");
				break;
			case "+b":
			case "ban":
				fwrite($irc,"PRIVMSG ".(($channel==$botnick)?"$nick ":"$channel "). ":$nick, ".help("ban","data")."\r\n");
				fwrite($irc,"PRIVMSG $channel :$nick, ".help("ban","see")."\r\n");
				break;
			case "+q":
			case "quiet":
				fwrite($irc,"PRIVMSG ".(($channel==$botnick)?"$nick ":"$channel "). ":$nick, ".help('q')."\r\n");
				break;
			case "+I":
			case "invex":
				fwrite($irc,"PRIVMSG ".(($channel==$botnick)?"$nick ":"$channel "). ":$nick, ".help('I')."\r\n");
				break;
			case "+R":
	                        fwrite($irc,"PRIVMSG ".(($channel==$botnick)?"$nick ":"$channel "). ":$nick, ".help('R')."\r\n");
	                	break;
			case "+d":
	                        fwrite($irc,"PRIVMSG ".(($channel==$botnick)?"$nick ":"$channel "). ":$nick, ".help('d')."\r\n");
	                	break;
	                case "ban_forwarding":
			case "ban forwarding":
			case "forwarding":
	                        fwrite($irc,"PRIVMSG ".(($channel==$botnick)?"$nick ":"$channel "). ":$nick, ".help('ban forwarding')."\r\n");
	                	break;
	                case "~":
	                        fwrite($irc,"PRIVMSG ".(($channel==$botnick)?"$nick ":"$channel "). ":$nick, ".help('~','data')."\r\n");
				fwrite($irc,"PRIVMSG ".(($channel==$botnick)?"$nick ":"$channel "). ":$nick, ".help("~","see")."\r\n");
	                	break;
	                case "\$a":
			case "a":
	                        fwrite($irc,"PRIVMSG ".(($channel==$botnick)?"$nick ":"$channel "). ":$nick, ".help("a")."\r\n");
	                	break;
	                case "\$r":
			case "r":
	                        fwrite($irc,"PRIVMSG ".(($channel==$botnick)?"$nick ":"$channel "). ":$nick, ".help('r')."\r\n");
	                	break;
	                case "SSL":
			case "ssl":
	                        fwrite($irc,"PRIVMSG ".(($channel==$botnick)?"$nick ":"$channel "). ":$nick, ".help('ssl')."\r\n");
	                	break;
	                case "ident":
	                        fwrite($irc,"PRIVMSG ".(($channel==$botnick)?"$nick ":"$channel "). ":$nick, ".help('ident')."\r\n");
	                	break;
		} 
	}
        ####################################
        #       Memory Usage Function
        ####################################
	
	if(stripos($data,"$botnick: mystats")){
		$uptime = system("uptime");
		fwrite($irc,"PRIVMSG $channel :$uptime\r\n");
		$debug = "mystats";
		debug_out($debug,$rejoin,$channel);
		usage($debug);
	}

        ####################################
        #         Restart Function
        ####################################

	if(stripos($data,"$botnick: restart") && hasPriv('restart')) {
		$pid = posix_getpid(); 
		posix_kill($pid, SIGINT);
		//We use Crontab! :o
		
		$debug = "restart";
		$posix_err = posix_strerror(posix_get_last_error());
		debug_out($debug,$posix_err,$channel);
	}
	
	####################################
	#            Die Function
	####################################

	if(stripos($data,"$botnick: die") && hasPriv('die')){

		$crontab = shell_exec('crontab -l');
		$dirname = dirname(__FILE__);
		file_put_contents($dirname . '/crontab', preg_replace('/(.*) (.*) \* \* \* \/usr\/local\/bin\/phoenix/', '#\1 \2 * * * /usr/local/bin/phoenix', $crontab));
		shell_exec('crontab ' . $dirname . '/crontab');
		posix_kill(posix_getppid(), SIGTERM);
		if(posix_get_last_error()!= 0){
			$posixErrNo = posix_get_last_error();
			echo posix_strerror($posixErrNo);
			if($debugChan) fwrite($irc,"PRIVMSG $debugChan :" . posix_strerror($posixErrNo) . "\r\n");
		}
	}

        ####################################
        #           Math Function 
        ####################################
	
	//This Function is being worked on in BETA

        ####################################
        #             Off Function
        ####################################

        if(stripos($data, "$botnick: off") && hasPriv('off')) {
                $users['*!*@*'];
                $users['*!*@*'] = 'ignore';
		$debug = "off";
		$null = NULL;
		debug_out($debug,$null,$channel);
		usage($debug);
        }

	####################################
	#             On Function
	####################################

        if(stripos($data,"$botnick: on") && hasPriv('on')) {
		$muted = 'base';
                $users['*!*@*'] = $muted;
		$debug = "on";
		debug_out($debug,$null,$channel);
		usage($debug);
        }

        ####################################
        #           Eval Function
        ####################################

	if(stripos($data,"$botnick: eval") && hasPriv('eval')){
		$evalArr = explode("$botnick: eval ",$data);
		$evalTxt = $evalArr[1];
		if(eval_syntax($evalTxt)){
			$eval = eval($evalArr[1]);
		}
		$debug = "eval";
		debug_out($debug,$evalTxt,$channel);
		usage($debug);
	}

        ####################################
        #           Quit Function
        ####################################

	if(stripos($data,"$botnick: quit") && hasPriv('quit')){
		$quitTextArr = explode("$botnick: quit ",$data);
		$quitText    = $quitTextArr[1];
		
		$debug = "quit";
		debug_out($debug,$quitText,$channel);
		usage($debug);
		
		fwrite($irc,"QUIT :$quitText\r\n");
	}

	####################################
	#     Blacklist a User Function
	####################################

	//This Function is being worked on in BETA

	####################################
	#           Amsg Function
	####################################
	
	if(stripos($data,"$botnick: amsg") && hasPriv('amsg')){
		$amsgArr = explode("$botnick: amsg ",$data);
		$amsg    = $amsgArr[1];
		$chansArr = explode(",",$irc_var["chans"]);
		foreach($chansArr as $amsgChan){
			fwrite($irc,"PRIVMSG $amsgChan :$amsg\r\n");
		}
		$debug = "amsg";
		debug_out($debug,$amsg,$channel);
		usage($debug);
	}
	
	####################################
	#          History Function
	####################################

	if(stripos($data,"$botnick: history") && hasPriv('track')){
		$areParamsArr = explode("$botnick: history ",$data);
		$areParams    = $areParamsArr[1];
		if(($areParams != "") && ($areParams != " ")){
			get_usage($areParams);
			$historyDebug = 1;
		} else {
			fwrite($irc,"PRIVMSG $channel :".get_usage()."\r\n");
			$historyDebug = 2;
		}
		$debug = "history";
		if($historyDebug == 1){
			$request = trim(get_usage(),250) . "... (trucinated)";
		} elseif($historyDebug == 2){
			$request = trim(get_usage($areParams),250) . "... (trucinated)";
		} else {
			$request = "ERROR!  Error fetching history!";
		}
		debug_out($debug,$request,$channel);
		usage($debug);
	}

	####################################
	#  Debug-Only Notify Kick Function
	####################################
	
	if(stripos($data,"KICK #") && !stristr($data,"PRIVMSG")){
		$whoKickedMeArr1 = explode("KICK ",$data);
		$whoKickedMe     = $whoKickedMeArr1[1];
		$kickingUserArr  = explode("!",$data);
		$kickingUser     = $kickingUserArr[0];
		$kickingUser     = explode(":",$kickingUser);
		$kickingUser     = $kickingUser[1];

		if(stristr($whoKickedMe,"YamaBot")){
			$kickMeArr = explode(" ",$whoKickedMe);
			$kick[0] = $kickMeArr[0]; #channel
			$kick[1] = $kickMeArr[1]; #me
			$kick[2] = $kickMeArr[2];
			$kick[2] = explode(":",$kick[2]);
			$kick[2] = $kick[2][2];   #:reason
			$returnKick = "I was kicked from - ".$kick[0]." - BY - ".$kickingUser." - REASON - ".$kick[2];

			$iWasKicked = TRUE;

			$debug = "notify_kick";
			debug_out($debug,$returnKick,$channel);
		} else {
			$whoKickedMeArr1 = NULL;
			$whoKickedMe     = NULL;
		}
	}

	if(stripos($data,"$botnick") && stristr($data,":requested by")){
		$whoRemovedMeArr  = explode("requested by ",$data);
		$whoRemovedMeNick = $whoRemovedMeArr[1];
		$whoRemovedMeNick = explode(":",$whoRemovedMeNick);
		$whoRemovedMeNick = $whoRemovedMeNick[0];
		$RemoveExplode    = ":requested by " . $whoRemovedMeNick . ":";
		$whoRemovedMeMSG  = explode("$RemoveExplode",$data);
		$whoRemovedMeMSG  = $whoRemovedMeMSG[1];
		$whoRemovedMeChan = explode("PART ",$data);
		$whoRemovedMeChan = $whoRemovedMeChan[1];
		$whoRemovedMeChan = explode(" :",$whoRemovedMeChan);
		$whoRemovedMeChan = $whoRemovedMeChan[0];

		$iWasRemoved      = TRUE;

		$removeOut .= "REMOVE: I was removed from - ";
		$removeOut .= $whoRemovedMeChan;
		$removeOut .= " - BY- ";
		$removeOut .= $whoRemovedMeNick;
		$removeOut .= " - FOR - ";
		$removeOut .= $whoRemovedMeMSG;

		$debug = "remove";
		debug_out($debug,$removeOut,$channel);
	}

	####################################
	#     CTCP Responses Function
	####################################

	if($p[3] == chr(001) . "VERSION" . chr(001)) {
		$target = explode("!", $d[0]);
		$target = trim($target[0],":");
		$data = "NOTICE $target :";
		$data .= chr(001);
		$data .= "VERSION " . CTCPVersion;
		$data .= chr(001);
		$data .= "\r\n";
		fwrite($irc, $data);
	}
	if($p[3] == chr(001) . "TIME" . chr(001)) {
		$target = explode("!", $d[0]);
		$target = trim($target[0],":");
		$data = "NOTICE $target :";
		$data .= chr(001);
		$data .= "TIME " . $CTCPTime;
		$data .= chr(001);
		$data .= "\r\n";
		fwrite($irc, $data);
	}
	if($p[3] == chr(001) . "USERINFO" . chr(001)) {
		$target = explode("!", $d[0]);
		$target = trim($target[0],":");
		$data = "NOTICE $target :";
		$data .= chr(001);
		$data .= "USERINFO " . CTCPUserinfo;
		$data .= chr(001);
		$data .= "\r\n";
		fwrite($irc, $data);
	}
	if($p[3] == chr(001) . "CLIENTINFO" . chr(001)) {
		$target = explode("!", $d[0]);
		$target = trim($target[0],":");
		$data = "NOTICE $target :";
		$data .= chr(001);
		$data .= "CLIENTINFO " . CTCPClientinfo;
		$data .= chr(001);
		$data .= "\r\n";
		fwrite($irc, $data);
	}

	if($p[3] == chr(001) . "FINGER" . chr(001)) {
		$target = explode("!",$d[0]);
		$target = trim($target[0],":");
		$data = "NOTICE $target :";
		$data .= chr(001);
		$data .= "FINGER ". CTCPFINGER;
		$data .= "\r\n";
		    fwrite($irc, $data);
		}
	####################################
	#    AutoRejoin Function (/kick)
	####################################
	
	if($iWasKicked && $irc_var["autoRejoin"] == "yes"){
		fwrite($irc,"JOIN $kick[0]\r\n");
		$iWasKicked = FALSE;
	}

	####################################
	#   AutoRejoin Function (/remove)
	####################################

	if($iWasRemoved && $irc_var["autoRejoin"] == "yes"){
		fwrite($irc,"JOIN $whoRemovedMeChan\r\n");
		$iWasRemoved = FALSE;
	}

#########################################################################
#RECOMMENDED: clear our outstanding data, unless the user writes to
#             /dev/null
#########################################################################


	flush();

#########################################################################
#NOTE: close while(!feof($irc)){}########################################
#########################################################################

}

#########################################################################
#NOTE: End the php script (you may omit this if you always run php -r)###
#########################################################################

?>
